import React, { useState, useImperativeHandle, RefObject, useEffect } from 'react';
import { Modal, TreeSelect, Form, Input, Select, message } from 'antd';
import { IUser, IDepth } from '../../types/login';
import api from '../../api';
interface IProps {
  deptRef: RefObject<{
    showModal: (
      type: string,
      data?: IDepth | { parentId: string },
    ) => void,
  }>;
  upData: () => Promise<void>;
}

const App: React.FC<IProps> = (props) => {
  // 控制弹窗显示隐藏
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 获取部门列表
  const [deptList, setDeptList] = useState<IDepth[]>();
  // 用户列表
  const [userList, setUserList] = useState<IUser[]>();
  // action: add 新增 edit 编辑
  const [action, setAction] = useState<string>('add');
  const [form] = Form.useForm();
  const showModal = (type: string, data?: IDepth | { parentId: string }) => {
    setAction(type);
    form.setFieldsValue(data);
    setIsModalOpen(true);
  };

  const handleOk = () => {
    // 校验form
    form.validateFields().then(() => {
      if (action === 'add') addDeptApi(form.getFieldsValue());
      else if (action === 'edit') editDeptApi(form.getFieldsValue());
    })

  };
  // 取消
  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };

  // 获取部门数据
  const getDepthData = async () => {
    const data = await api.getDeptList();
    setDeptList(data);
  }
  // 获取用户列表
  const getUserListData = async () => {
    const data = await api.getUserList();
    setUserList(data);
  };

  // 新增部门
  const addDeptApi = async (params: IDepth) => {
    await api.addDept(params);
    message.success('添加成功');
    handleCancel();
    props.upData();
  }
  // 编辑部门
  const editDeptApi = async (params: IDepth) => {
    await api.editDept(params);
    message.success('编辑成功');
    handleCancel();
    props.upData();
  }

  useEffect(() => {
    getDepthData();
    getUserListData();
  }, []);

  useImperativeHandle(props.deptRef, () => ({
    showModal
  }));

  return (
    <>
      <Modal
        title={
          action === 'add' ? '新增部门' : '编辑部门'
        }
        maskClosable={false}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} preserve={false} labelAlign="right" labelCol={{ span: 4 }}>
          <Form.Item
            label="上级部门"
            name="parentId"
          >
            <TreeSelect
              showSearch
              placeholder="请选择上级部门"
              allowClear
              treeDefaultExpandAll
              treeData={deptList}
              fieldNames={{ label: 'deptName', value: '_id' }}
            />

          </Form.Item>
          <Form.Item
            label="部门名称"
            name="deptName"
            rules={[{ required: true, message: '请输入部门名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="负责人"
            name="userName"
            rules={[{ required: true, message: '请选择负责人' }]}
          >
            <Select>
              {userList?.map((item) => (
                <Select.Option key={item._id} value={item.userName}>
                  {item.userName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default App;